package logic

import (
	"context"
	"errors"
	"fmt"
	"gorm.io/gorm"
	"house/cache"
	"house/models"
	"math/rand"

	"house/houserpc/houserpc"
	"house/houserpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *houserpc.LoginRequest) (*houserpc.LoginResponse, error) {
	// todo: add your logic here and delete this line
	var user models.User
	models.DB.Where("mobile=?", in.Mobile).Find(&user)
	if user.ID == 0 {
		user = models.User{
			Model:     gorm.Model{},
			Mobile:    in.Mobile,
			Password:  in.Password,
			HeadImage: "https://ts3.tc.mm.bing.net/th/id/OIP-C.rPQTtL06uTRQSkiUvIGykwAAAA?r=0&cb=thfc1&rs=1&pid=ImgDetMain&o=7&rm=3",
			NickName:  fmt.Sprintf("用户_%d", rand.Intn(9000)+1000),
		}
		if in.SendSmsCode == "" {
			return nil, errors.New("验证码不能为空")
		}
		data, _ := cache.Rdb.Get(l.ctx, "send"+in.Mobile).Result()
		if in.SendSmsCode != data {
			return nil, errors.New("验证码错误请重新输入")
		}
		models.DB.Create(&user)
	} else {
		if in.Password == "" {
			data, _ := cache.Rdb.Get(l.ctx, "send"+in.Mobile).Result()
			if in.SendSmsCode != data {
				return nil, errors.New("验证码错误请重新输入")
			}
		} else {
			if in.Password != user.Password {
				return nil, errors.New("密码错误请重新输入")
			}
		}
	}
	return &houserpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
